import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import LayOut from "../views/layout/LayOut.vue";
import {$localStorage} from "@/utils/utils"
const routes = [
  {
    path: "/",
    redirect: "/layout/home",
  },
  {
    path: "/layout",
    name: "layout",
    component: LayOut,
    children: [
      {
        path: "home",
        name: "home",
        component: HomeView,
        meta: {
          title: "Home",
        },
      },
      {
        path: "about",
        name: "about",
        component: () => import("../views/AboutView.vue"),
      },
      {
        path: "map3d",
        name: "map3d",
        component: () => import("@/views/map/index.vue"),
      }
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/Login.vue"),

  },
  // 404 页面
  {
    path: "/:pathMatch(.*)*",
    name: "notFound",
    component: () => import("../views/NotFoundView.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});
// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!$localStorage.getItem('token') // 检查是否存在 token

  // 如果目标路由不是登录页，并且没有 token，则重定向到登录页面
  if (to.name !== 'login' && !isAuthenticated) {
    next({ name: 'login' });
  } else {
    next(); // 继续导航
  }
});


export default router;
